name: LABEL ACTION

on:
  pull_request_target:
    types:
      - labeled
      - unlabeled

permissions:
  checks: write
  actions: write
  contents: write
  deployments: write
  discussions: write
  issues: write
  packages: write
  pages: write
  pull-requests: write
  repository-projects: write
  security-events: write
  statuses: write

jobs:
  meta-review:
    name: META REVIEW LABEL
    if: github.event.label.name == 'META-REVIEW'
    runs-on: ubuntu-latest
    env:
      PR_NUMBER: ${{ github.event.pull_request.number }}
      META_TEAM: meta-committer

    steps:
      - name: ADD REVIEWER
        if: github.event.action == 'labeled'
        run: |
          curl -L \
            -X POST \
            -H "Accept: application/vnd.github+json" \
            -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
            -H "X-GitHub-Api-Version: 2022-11-28" \
            "https://api.github.com/repos/${{ github.repository }}/pulls/${PR_NUMBER}/requested_reviewers" \
            -d "{\"team_reviewers\":[\"${META_TEAM}\"]}" 2>/dev/null

      - name: REMOVE REVIEWER
        if: github.event.action == 'unlabeled'
        run: |
          curl -L \
            -X DELETE \
            -H "Accept: application/vnd.github+json" \
            -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
            -H "X-GitHub-Api-Version: 2022-11-28" \
            "https://api.github.com/repos/${{ github.repository }}/pulls/${PR_NUMBER}/requested_reviewers" \
            -d "{\"reviewers\":[], \"team_reviewers\":[\"${META_TEAM}\"]}" 2>/dev/null

  proto-review:
    name: PROTO REVIEW LABEL
    if: github.event.label.name == 'PROTO-REVIEW'
    runs-on: ubuntu-latest
    env:
      PR_NUMBER: ${{ github.event.pull_request.number }}
      PROTO_TEAM: proto-team

    steps:
      - name: ADD REVIEWER
        if: github.event.action == 'labeled'
        run: |
          curl -L \
            -X POST \
            -H "Accept: application/vnd.github+json" \
            -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
            -H "X-GitHub-Api-Version: 2022-11-28" \
            "https://api.github.com/repos/${{ github.repository }}/pulls/${PR_NUMBER}/requested_reviewers" \
            -d "{\"team_reviewers\":[\"${PROTO_TEAM}\"]}" 2>/dev/null

      - name: REMOVE REVIEWER
        if: github.event.action == 'unlabeled'
        run: |
          curl -L \
            -X DELETE \
            -H "Accept: application/vnd.github+json" \
            -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
            -H "X-GitHub-Api-Version: 2022-11-28" \
            "https://api.github.com/repos/${{ github.repository }}/pulls/${PR_NUMBER}/requested_reviewers" \
            -d "{\"reviewers\":[], \"team_reviewers\":[\"${PROTO_TEAM}\"]}" 2>/dev/null
